package com.mengjiahui.auduoplayer.fragment;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mengjiahui.auduoplayer.service.NativeMusicService;
import com.mengjiahui.auduoplayer.R;
import com.mengjiahui.auduoplayer.adapter.NativeMusicAdapter;
import com.mengjiahui.auduoplayer.bean.Music;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Meng
 * @data 2020/5/9
 */
public class MainFragment extends Fragment {
    private final String[] projection = {MediaStore.Audio.Media._ID //：音乐ID
            , MediaStore.Audio.Media.DISPLAY_NAME //：音乐文件名
            , MediaStore.Audio.Media.TITLE //：歌曲名
            , MediaStore.Audio.Media.DURATION //：音乐时长
            , MediaStore.Audio.Media.ARTIST //：歌手名
            , MediaStore.Audio.Media.ALBUM //：专辑名
            , MediaStore.Audio.Media.YEAR //：年代
            , MediaStore.Audio.Media.MIME_TYPE //：音乐格式
            , MediaStore.Audio.Media.SIZE //：文件大小
            , MediaStore.Audio.Media.DATA //：文件路径
            , MediaStore.Audio.Media.IS_MUSIC //：是否为音乐
            , MediaStore.Audio.Media.ALBUM_ID //：专辑ID
    };
    private final String[] iconProjection = new String[]{
            "album_art"
    };
    private RecyclerView recyclerView;
    private List<Music> musicList=new ArrayList<>();
    private View view;
    public NativeMusicService.MyBinder myBinder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder=(NativeMusicService.MyBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main, container, false);
        if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {//检查是否有权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);//没有权限请求授权
        } else {
            show();
        }
        return view;
    }

    private void show() {
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
        while (cursor.moveToNext()) {
            Uri uri = Uri.parse("content://media/external/audio/albums/" + cursor.getColumnIndex(MediaStore.Audio.Media._ID));
            Cursor iconCursor = contentResolver.query(uri, iconProjection, null, null, null);
//            String album_art = iconCursor.getString(iconCursor.getColumnIndex("album_art"));
//            Bitmap bitmap = BitmapFactory.decodeFile(album_art);
            Music music = new Music();
            music.setMusicId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)));
            music.setAlbumId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
            music.setMusicName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
            music.setAlbum(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
            music.setAuthor(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
            music.setDisplayName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
            musicList.add(music);
        }
        NativeMusicAdapter nativeMusicAdapter=new NativeMusicAdapter(musicList);
        recyclerView=view.findViewById(R.id.recyclerViewNative);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(null);
        recyclerView.setLayoutManager(linearLayoutManager);
        nativeMusicAdapter.setListener((music -> {
            TextView ToolarBottomMusicName=getActivity().findViewById(R.id.textViewToolbarBottomMusicName);
            TextView ToolarBottomMusicAuthor=getActivity().findViewById(R.id.textViewToolbarBootomMuscicAuthor);
            ToolarBottomMusicAuthor.setText(music.getAuthor());
            ToolarBottomMusicName.setText(music.getMusicName());
            Intent intent=new Intent(view.getContext(),NativeMusicService.class);
            intent.putExtra("music",(Serializable)musicList);
            intent.putExtra("CURRENT_POSITION",musicList.indexOf(music));
            view.getContext().startService(intent);
            view.getContext().bindService(intent,connection, Service.BIND_AUTO_CREATE);
        }));
        recyclerView.setAdapter(nativeMusicAdapter);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        System.out.println(requestCode);
        switch (requestCode) {
            case 0:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    show();
                } else {
                    Toast.makeText(getContext(), "Permission Deny", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
